package com.liveinstars.activity.application.endpoint;

import com.liveinstars.activity.application.assembler.ActivityAssembler;
import com.liveinstars.activity.application.service.ActivityApplicationService;
import com.liveinstars.activity.business.activity.entity.ActivityDO;
import com.liveinstars.api.dto.*;
import com.liveinstars.api.facade.IActivityApi;
import com.liveinstars.api.query.ActivityNewQuery;
import com.onepiece.shipelves.common.Result;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.exception.QuHuiRuntimeException;
import com.onepiece.shipelves.common.vo.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(value = "活动api接口")
@RestController
public class ActivityEndpoint implements IActivityApi {
    private static final Logger logger = LoggerFactory.getLogger(ActivityEndpoint.class);



    @Autowired
    ActivityApplicationService activityApplicationService;

    //属于全部活动的查询,非活动列表中的和我有关的活动列表
    @ApiOperation(value="活动列表查询", notes="活动列表查询")
    @Override
    public Result<Page<ActivityDto>> pageByQuery(@RequestBody ActivityNewQuery query) {
        Result<Page<ActivityDto>> result = new Result<>();
        try {
            if (query.getPageSize() > 50) {
                query.setPageSize(50);
            }

            Page<ActivityDto> page = activityApplicationService.pageByQuery(query);
            result.setData(page);
        } catch (Exception e) {
            result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
        }
        return result;
    }

//    @Override
//    public Result<Page<ActivityDto>> getAllActivitys(@RequestBody ActivityNewQuery query) {
//        Result<Page<ActivityDto>> result = new Result<>();
////        try {
////            if (query.getPageSize() > 50) {
////                query.setPageSize(50);
////            }
////            Page<ActivityDO> pageDos = activityApplicationService.getAllActivitys(query);
////
////            Page<ActivityDto> page = new Page<ActivityDto>(ActivityAssembler.toDTOS(pageDos.getList()),
////                    pageDos.getPageNum(),
////                    pageDos.getPageSize(),
////                    pageDos.getTotalCount()
////            );
////            result.setData(page);
////        } catch (Exception e) {
////            result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
////        }
//        return result;
//    }
//
//    @Override
//    public Result<Page<ActivityDto>> getGroupActivitys(@RequestBody ActivityNewQuery query) {
//
//        Result<Page<ActivityDto>> result = new Result<>();
////        try {
////            if (query.getPageSize() > 50) {
////                query.setPageSize(50);
////            }
////            Page<ActivityDO> pageDos = activityApplicationService.getGroupActivitys(query);
////
////            Page<ActivityDto> page = new Page<ActivityDto>(ActivityAssembler.toDTOS(pageDos.getList()),
////                    pageDos.getPageNum(),
////                    pageDos.getPageSize(),
////                    pageDos.getTotalCount()
////            );
////            result.setData(page);
////        } catch (Exception e) {
////            result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
////        }
//        return result;
//    }
//


    /**
     * 关联了用户的小圈，并且根据条件加入招募活动
     * @param query
     * @param userId
     * @return
     */
    @ApiOperation(value="活动列表新查询", notes="活动列表查询")
    @Override
    public Result<Page<ActivityDto>> pageByNewQuery(@RequestBody ActivityNewQuery query, @RequestHeader("uid") Integer userId) {
        Result<Page<ActivityDto>> result = new Result<>();
        try {
            if (query.getPageSize() > 50) {
                query.setPageSize(50);
            }
            Page<ActivityDO> pageDos = activityApplicationService.pageByNewQuery(query, userId);

            Page<ActivityDto> page = new Page<ActivityDto>(ActivityAssembler.toDTOS(pageDos.getList()),
                    pageDos.getPageNum(),
                    pageDos.getPageSize(),
                    pageDos.getTotalCount()
            );
            result.setData(page);
        } catch (Exception e) {
            logger.error("pageByNewQuery activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }
    @ApiOperation(value="活动详情", notes="活动详情")
    @Override
    public Result<ActivityDetailDto> getDetailById(@RequestParam(value = "id") Integer id, @RequestHeader("uid") Integer userId) {
        Result<ActivityDetailDto> result = new Result<>();
        try {
            ActivityDO detail = activityApplicationService.getDetailById(id);

            List<ActivityMemberDto> members = activityApplicationService.getJoinMembers(id);
            ActivityDetailDto activityDetailDto = ActivityAssembler.toDTO(detail);
            activityDetailDto.setJoinMembers(members);
            activityDetailDto.setJoinMemberNum(members.size());
            Boolean isApply = activityApplicationService.getIsApply(userId, id);
            activityDetailDto.setIsApply(isApply);
            Boolean isLike = activityApplicationService.getIsLike(userId, id);
            activityDetailDto.setIsLike(isLike);
            long count = members.stream().filter((m) -> m.getUserId().equals(userId)).count();
            activityDetailDto.setIsJoined(count > 0);
            result.setData(activityDetailDto);
        } catch (Exception e) {
            logger.error("getdetailbyid activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Result<Boolean> viewActivity(@RequestParam(value = "id") Integer id) {
        Result<Boolean> result = new Result<>();
        try {
            Boolean isSuccess = activityApplicationService.viewActivity(id);
            result.setData(isSuccess);
        } catch (Exception e) {
            logger.error("view activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Result<Boolean> likeActivity(@RequestParam(value = "id") Integer id,@RequestHeader("uid") Integer userId) {

        Result<Boolean> result = new Result<>();
        try {
            Boolean isSuccess = activityApplicationService.likeActivity(id, userId, true);
            result.setData(isSuccess);
        } catch (Exception e) {
            logger.error("view activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Result<Boolean> unLikeActivity(@RequestParam(value = "id") Integer id,@RequestHeader("uid") Integer userId) {
        Result<Boolean> result = new Result<>();
        try {
            Boolean isSuccess = activityApplicationService.likeActivity(id, userId, false);
            result.setData(isSuccess);
        } catch (Exception e) {
            logger.error("view activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }


    @Override
    public Result<List<ActivityDto>> getActivitys(@RequestParam(value = "user_id") Integer userId) {
        Result<List<ActivityDto>> result = new Result<>();
        try {
            result.setData(activityApplicationService.getActivitys(userId));
        } catch (Exception e) {
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }




    @Override
    public Result<Boolean> updateStatus(@RequestParam("activityId") Integer activityId,
                                        @RequestParam("status") int status) {
        Result<Boolean> result = new Result<>();
        try {
            Boolean isSuccess = activityApplicationService.updateStatus(activityId, status);
            result.setData(isSuccess);
        } catch (Exception e) {
            logger.error("updateStatus activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Result<List<ActivityDto>> getApplyActivitys(@RequestParam(value = "user_id") Integer userId) {
        Result<List<ActivityDto>> result = new Result<>();
        try {
            result.setData(ActivityAssembler.toDTOS(activityApplicationService.getApplyActivity(userId)));
        } catch (Exception e) {
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }


    @ApiOperation(value="创建活动", notes="创建活动")
    @Override
    public Result<ActivityDetailDto> create(@RequestBody ActivityCreateDto dto) {

        Result<ActivityDetailDto> result = new Result<>();
        try {
            ActivityDO activityDO = ActivityAssembler.toDO(dto);
            ActivityDO detail = activityApplicationService.createActivity(activityDO);
            if (detail == null) {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            } else {
                result.setData(ActivityAssembler.toDTO(detail));
            }
        } catch (Exception e) {
            logger.error("create activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @ApiOperation(value="更新活动", notes="更新活动")
    @Override
    public Result<ActivityDetailDto> updateById(@RequestBody ActivityCreateDto dto, @RequestParam(value = "activityId") Integer activityId) {
        Result<ActivityDetailDto> result = new Result<>();
        try {
            ActivityDO activityDO = ActivityAssembler.toDO(dto);
            ActivityDO detail = activityApplicationService.updateActivityById(activityDO, activityId);
            if (detail == null) {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            } else {
                result.setData(ActivityAssembler.toDTO(detail));
            }
        } catch (Exception e) {
            logger.error("create activity", e);
            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Result deleteById(@RequestParam(value = "id") Integer id) {
        return null;
    }

    @ApiOperation(value="获取问题", notes="获取活动问题")
    @Override
    public Result<List<QuestionDto>> getQuestion(@RequestParam(value = "activityId") Integer activityId) {
        Result<List<QuestionDto>> result = new Result<>();
        List<QuestionDto> questionDtos = activityApplicationService.getQuestions(activityId);
        if(questionDtos != null){
            result.setData(questionDtos);
            return result;
        }
        return SystemExceptionEnum.UN_KNOW_ERROR.createResult();
    }

    @ApiOperation(value="申请加入活动", notes="申请加入活动")
    @Override
    public Result<Boolean> joinActivity(@RequestBody ActivityApprovalDto dto) {
        Result<Boolean> result = new Result<>();
        try {
            Boolean isSuccess = activityApplicationService.joinActivity(dto.getActivityId(), dto.getUserId(), dto.getReqMsg());
            result.setData(isSuccess);
        }catch (Exception e) {
            logger.error("joinactivity", e);

            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }

        return result;
    }

    @ApiOperation(value="获取活动成员", notes="获取活动成员")
    @Override
    public Result<List<ActivityMemberDto>> getActivityMember(@RequestParam(value = "activityId", defaultValue = "") Integer activityId) {
        Result<List<ActivityMemberDto>> result = new Result<>();

        try {
            List<ActivityMemberDto> memberDtos = activityApplicationService.getJoinMembers(activityId);
            result.setData(memberDtos);
        }catch (Exception e) {
            logger.error("getactivitymember", e);

            if (e instanceof QuHuiRuntimeException) {
                result = ((QuHuiRuntimeException) e).createResult();
            } else {
                result = SystemExceptionEnum.UN_KNOW_ERROR.createResult();
            }
        }
        return result;
    }

    @Override
    public Boolean addActivityMember(@RequestParam(value = "fromId") Integer fromId, @RequestParam(value = "userId") Integer userId, @RequestParam(value = "groupId") Integer groupId) {
        return activityApplicationService.addActivityMember(fromId, userId, groupId);
    }

//    @Override
//    public Result<String> testReturn(@RequestBody ActivityDto vo) {
//        Result<String> result = new Result<>();
//        result.setData("pheQwCiWhxvUlQiZbNJn1Qndf9ElaC0ThlP5Xvqnq6L123w5C4cd5346Y0fVDzrI2MhqK/dRFbfknoqzl2Radj9YRbHFv4Z0mPKEMXJtvpyA8ExkKe7f1jwziTg7wmk4obD7k+1KtktSmz/0N7iLtNUZlWv2fbHffscjwdqPgyQ8mHSPT8uAcx63sSEdhgqmm7Ff8VdT2+TEfVRXkdPP9DAAy33aNmLsUjg4b6+pVvjXH9vaDxShsI7L3xH7zTkXynmk+owf0sKlGLuYc/iB3ob5XrBZqq+EvVAYyoUuFNC8oGVHzaJTPujcgovpffm393CWW7oGI8WHJ2cCN/tVKz/NyXysMOQk4PjraxWyt27o/pim6hCYqIF0fmJ5ckKS35dHQnz8mOrp8ijSZMatDA==,JcjGRrnZGKhMEBIYVBVQNZC9kPoYFjxvrWDmDp3FrcWQudT1FzfpXLCYFQry9+p5aIGgerY0IRW2M9H44PcJaC3ockEz7Zb2tKoGq2t0x5PXNW7fG7SHqbEbzoNepRL869AP8HBAIFSUMqlYrZrLptm+rgXWD+bRT0ox6roXsNM=");
//        return result;
//    }
//
//    @Override
//    public Result<Boolean> testBool() {
//        Result<Boolean> result = new Result<>();
//        result.setData(true);
//        return result;
//    }


}
